import os
import re

# 输入 SRT 文件夹
input_folder = r"C:\Users\33720\Desktop\xmly27\srt"
output_folder = r"C:\Users\33720\Desktop\Srtout"
os.makedirs(output_folder, exist_ok=True)

def srt_time_to_ass(time_str):
    """SRT 时间格式 -> ASS 时间格式"""
    h, m, s = time_str.split(":")
    s, ms = s.split(",")
    return f"{int(h)}:{int(m):02d}:{int(s):02d}.{int(ms)//10:02d}"

def convert_srt_to_ass(srt_file, ass_file):
    with open(srt_file, "r", encoding="utf-8") as f:
        srt_content = f.read().strip()

    # ASS 文件头（样式部分）
    ass_header = """[Script Info]
ScriptType: v4.00+
PlayResX: 1920
PlayResY: 1080
Collisions: Normal
ScaledBorderAndShadow: yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: JP, Arial,72,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,3,0,2,10,10,40,1
Style: CN, Arial,48,&H00FFFF00,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
"""

    ass_lines = []

    # 匹配 SRT 区块
    pattern = re.compile(r"(\d+)\s+([\d:,]+)\s+-->\s+([\d:,]+)\s+([\s\S]*?)(?=\n\d+\n|$)", re.MULTILINE)
    matches = pattern.findall(srt_content)

    for _, start, end, text in matches:
        start_time = srt_time_to_ass(start.strip())
        end_time = srt_time_to_ass(end.strip())
        lines = [line.strip() for line in text.strip().split("\n") if line.strip()]

        if len(lines) == 1:
            jp_text = lines[0]
            cn_text = ""  # 没有翻译
        elif len(lines) >= 2:
            jp_text = lines[0]
            cn_text = lines[1]
        else:
            continue

        # 上面日语（大字）
        ass_lines.append(f"Dialogue: 0,{start_time},{end_time},JP,,0,0,0,,{jp_text}")
        # 下面中文（小字）
        if cn_text:
            ass_lines.append(f"Dialogue: 0,{start_time},{end_time},CN,,0,0,0,,{cn_text}")

    with open(ass_file, "w", encoding="utf-8") as f:
        f.write(ass_header + "\n".join(ass_lines))

    print(f"已生成: {ass_file}")

# 批量处理文件夹
for filename in os.listdir(input_folder):
    if filename.lower().endswith(".srt"):
        input_path = os.path.join(input_folder, filename)
        output_path = os.path.join(output_folder, os.path.splitext(filename)[0] + ".ass")
        convert_srt_to_ass(input_path, output_path)

print("全部 SRT 已转换为 ASS ✅")
